from flask import request, jsonify
import functools
from util import PWT
from util import Role


# 自定义错误响应
def json_response(data, code=200):
    response = jsonify(data)
    response.status_code = code
    return response


# 权限验证装饰器
def role_authorization(required_role=None):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            token = request.args.get("token")
            if not token:
                return json_response({"code": "LOGIN_OUT", "message": "Token is required"}, code=401)

            if required_role == Role.MANAGER:
                try:
                    decoded_jwt = PWT.verify(token)
                    user_role = decoded_jwt.get("role")
                    if user_role != required_role:
                        return json_response({"code": "PERMISSION_DENY", "message": "Permission denied"}, code=403)

                    return func(*args, **kwargs)

                except Exception as e:
                    return json_response({"code": "LOGIN_OUT", "message": "Invalid or expired token"}, code=401)

            if required_role == Role.USER:
                try:
                    decoded_jwt = PWT.verify(token)
                    user_role = decoded_jwt.get("role")
                    return func(*args, **kwargs)
                except Exception as e:
                    return json_response({"code": "LOGIN_OUT", "message": "Invalid or expired token"}, code=401)

        return wrapper

    return decorator
